package com.code2roc.jarmanage.servlet.filemanage;

import com.code2roc.jarmanage.db.ConfigDB;
import com.code2roc.jarmanage.model.ConfigDO;
import com.code2roc.jarmanage.model.Result;
import com.code2roc.jarmanage.util.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;

public class SystemFileDetailServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Result result = Result.okResult();
        HashMap paramMap = CommonUtil.getParamMap(req);
        String prefix = ConvertUtil.convert2String(paramMap.get("prefix"));
        String fileName = ConvertUtil.convert2String(paramMap.get("fileName"));
        String basePath = EnviromentUtil.getFileRootHomePath();
        String filePath = basePath + prefix + fileName;
        Path path = Paths.get(filePath);
        int maxFileSize = ConvertUtil.convert2Int(ConfigUtil.getConfigValue("watchFileMaxSize"));
        long totalSpaceMB = Files.size(path) / (1024 * 1024);
        if (totalSpaceMB > maxFileSize) {
            result = Result.errorResult();
            result.setMsg("文件超过" + maxFileSize + "M，请下载查看");
            resp.getWriter().println(result.toString());
            return;
        }
        String fileContent = FileUtil.readFileContentManage(filePath);
        result.add("obj",fileContent);
        resp.getWriter().println(result.toString());
    }
}
